<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class SocietyApply extends Backend
{

    /**
     * SocietyApply模型对象
     * @var \app\admin\model\SocietyApply
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\SocietyApply;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','status','chamber_type_name','name','name_en','createtime']);
                $row->visible(['user']);
				$row->getRelation('user')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        //查询申请用户姓名
        $row["nickname"] = Db::name("user")->where("id = " . $row["uid"])->find()["nickname"] ?? "";

        if (false === $this->request->isPost()) {
            
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    //导出数据
    public function export()
    {
        set_time_limit(0);//设置时间限制
        $ids = $this->request->post('ids'); //获取数据的所有id

        //导出的字段
        $field = [
            'user>nickname',
            'status',
            'chamber_type_name',
            'name',
            'name_en',
            'sex',
            'idCard_no',
            'address',
            'address_en',
            'mobile',
            'fax',
            'email',
            'education_name',
            'work_years',
            'function_con',
            'speciality',
            'social',
            'institution_name',
            'business_reg_no',
            'business_createtime',
            'position',
            'position_en',
            'business_address',
            'business_address_en',
            'business_mobile',
            'business_fax',
            'business_email',
            'business_http',
            'business_facebook',
            'business_type_name',
            'business_service',
            'business_local_peo_num',
            'business_overseas_peo_num',
            'parent_name',
            'parent_name_en',
            'parent_no',
            'parent_chamber_name',
            'parent_mobile',
            'parent_fax',
            'parent_email',
            'createtime',
            'updatetime'
        ];
        //连表数据需要显示的字段，user>mobile表示为：user表下的mobile字段
        $fieldComment = [
            'user>nickname' => '用户昵称',
        ];
        $fields = $this->getField($field, "society_apply");

        $objPHPExcel = new Spreadsheet();
        $firstChar = 65;
        $tempChar = '';
        $tempCharNum = '';
        foreach ($fields as $key => &$field) {
            //当列超出 A-Z时，为：AA-AZ,BA-BZ，以此类推
            if ($firstChar > 90) {
                $firstChar = 65; //当超出 Z 时，重新跳到 A 开始

                if ($tempChar == '') {
                    $tempCharNum = 65;//当超出 Z 时，从 A 开始时需要加上 A-Z
                } else {
                    $tempCharNum += 1;
                }
                $tempChar = chr($tempCharNum);
            }
            $column = chr($firstChar);
            $firstChar++;

            $char = $tempChar . $column; //哪一列

            //处理连表的导出字段
            if (is_numeric($field)) {
                $field = [
                    'field' => $key,
                    'comment' => $fieldComment[$key],
                    'type' => 'varchar',
                    'chose' => [],
                ];
            }
            $field['char'] = $char;//记录哪一列，数据循环时可直接取用
            //设置表头
            $objPHPExcel->getActiveSheet()->setCellValue($char . '1', $field['comment']);
            //改变长度
            $objPHPExcel->getActiveSheet()->getColumnDimension($char)->setWidth(30);
        }


        //查询数据
        $wheres = [
        
        ];
        if ($ids != 'all' && !empty($ids)) {
            $wheres['society_apply.id'] = ['in', $ids];
        }
        $list = $this->model
            ->with(['user'])
            ->where($wheres)
            ->select();

        //输出表格
        foreach ($list as $key => &$val) {
            $val = $val->toArray();
            $i = $key + 2;//表格是从2开始的,第1行为表头
            foreach ($fields as &$field) {
                $data = $val[$field['field']] ?? '';

                //连表显示的字段
                if (strpos($field['field'], '>') !== false) {
                    $fieldArr = explode('>', $field['field']);
                    $data = $val[$fieldArr[0]][$fieldArr[1]];
                }
                //转换为时间格式
                if (is_numeric($data) && mb_strlen($data) == 10) {
                    $data = date('Y-m-d H:i:s', $data);
                }
                //将选择项转换成对应的值
                if (!empty($field['chose'])) {
                    $data = $field['chose'][$data];
                }
                //将char和varchar数据类型的单元格设置为文本类型，以防出现科学计数法
                if (strpos($field['type'], 'char') !== false) {
                    $objPHPExcel->getActiveSheet()->setCellValueExplicit($field['char'] . $i, $data, 's');
                } else {
                    $objPHPExcel->getActiveSheet()->setCellValue($field['char'] . $i, $data);
                }
            }
        }

        $outputFileName = date("YmdHis") . '导出.xls';

        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $outputFileName . '"');
        header("Content-Transfer-Encoding: binary");
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Xlsx');
        $objWriter->save('php://output');
        exit;
    }

}
